package com.vueperson.vueperson.services.handle;

import com.vueperson.vueperson.dao.RoleJPA;
import com.vueperson.vueperson.dao.UserJPA;
import com.vueperson.vueperson.entity.Role;
import com.vueperson.vueperson.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class Role01_01 extends Role01 {

@Autowired
    RoleJPA roleJPA;
    @Autowired
    Role role;
    @Autowired
    User user;
    @Autowired
    UserJPA userJPA;
    @Qualifier("role01_2")
    @Autowired
    Role2 roleIf;


    @Override
    public void saveRole(String name, String nameZh) {

        int i=roleJPA.findByNameOrNameZh(name,nameZh).size();
        if (i!=0){
            System.out.println("已有用户名");
            return;
        }

        role.setNameZh(nameZh);
        role.setName(name);
        roleJPA.save(role);
    }

    @Override
    public void saveUser(String username, String password, String roleName) {

        if (roleIf.haveUser(username)) {
            return;
        }
       List<Role> r= roleJPA.findByName(roleName);


        if (!roleIf.haveRole(roleName)) {

            return;
        }

        //创建用户
        user.setUsername(username);
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String encodePassword=bCryptPasswordEncoder.encode(password);
        user.setPassword(encodePassword);

        //创建角色
        role=r.get(0);


        //关联

        role.getUser().add(user);
        user.setRole(role);

        //保存
        userJPA.save(user);

        System.out.println("保存成功");

    }




    public void t01(){
        System.out.println("wqwqwqwqwqw");
    }
}
